package com.zyh.kaoshi.test1;

import com.zyh.kaoshi.test1.domain.Student;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

/**
 * @Author zyh
 * @Date 2024/8/10 9:44
 * @Description 测试数据    111 zyh 21  222 cxk 22
 */

public class Test1 {
    public static void main(String[] args) {
        //创建TreeMap,创建比较器，按照年龄从小到大排序
        Map<Student, String> map = new TreeMap<>((o1, o2) -> {
            return o1.getAge() > o2.getAge() ? 1 : (o1.getAge() < o2.getAge() ? -1 : 0);
        });
        Scanner input = new Scanner(System.in);
        //死循环输入信息
        while (true) {
            System.out.println("请输入学生信息(按照学号，姓名，年龄的顺序输入，中间以空格隔开),输入exit停止输入：");
            String studentInfo = input.nextLine();
            if ("exit".equals(studentInfo)) {
                break;
            }
            try {
                //按照空格分割字符串
                String[] s = studentInfo.split(" ");
                Student student = new Student(s[1], Integer.parseInt(s[2]));
                map.put(student, s[0]);
            } catch (IndexOutOfBoundsException e) {
                System.out.println("请输入完整的信息！");
            }
        }
        //创建缓冲输出字符流
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day13-code\\src\\com\\zyh\\kaoshi\\test1\\Student.txt"));
            //打印集合
            System.out.println("学生信息如下：");
            //获取所有的key
            Set<Student> keySet = map.keySet();
            for (Student key : keySet) {
                //获取所有的value
                String value = map.get(key);
                //遍历输出
                System.out.println("学号:" + value + "姓名:" + key.getName() + "年龄:" + key.getAge());
                StringBuffer sb = new StringBuffer();
                sb.append("学号:" + value);
                sb.append("姓名:" + key.getName());
                sb.append("年龄:" + key.getAge());
                String student = sb.toString();
                bw.write(student);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关流
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

